﻿using System.Linq;
using System.Web.Mvc;
using MayhemServer.Services;
using MayhemServer.Models;
using System.IO;
using MayhemServer.Extensions;

namespace MayhemServer.Controllers {
    public class PackageController : Controller {
        private readonly IPackageService packageService;

        public PackageController(IPackageService packageService) {
            this.packageService = packageService;
        }

        public ActionResult List(int? pageIndex) {
            var model = packageService.GetPackages(pageIndex, 10);

            return View(model);
        }

        public ActionResult Details(string id) {
            var model = packageService.GetPackageDetails(id);
            if (model == null) {
                return HttpNotFound();
            }

            return View(model);
        }

        public ActionResult Download(string id)
        {
            var model = packageService.GetPackageDetails(id);
            if (model == null)
            {
                // not found
                return null;
            }
            var package = packageService.GetPackage(id);


            var packageDownloadService = new PackageDetailService() as IPackageDetailService;
            var packageDbId = packageDownloadService.GetPackageDetailId(package);

            packageDownloadService.Increment(packageDbId);
            
            var stream = System.IO.File.OpenRead(Server.MapPath(package.GetDownloadUrl()));
            
            return File(stream, "application/zip", string.Format("{0}.mayhem", package.GetFileName()));
        } 
    }
}
